package com.heima.admin.aspect;


import com.heima.admin.annotation.LogModule;
import com.heima.admin.mapper.LogMapper;
import com.heima.model.admin.pojos.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class loggingAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    @Around("execution(* com.heima.admin.controller..*.*(..))&&@annotation(com.heima.admin.annotation.LogModule)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Log operLog = new Log();
        //获取userId,时间
        String userId = request.getHeader("userId");
        operLog.setUserId(Integer.parseInt(userId));
        operLog.setCreateTime(LocalDateTime.now());
        //获取模块信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String module = method.getAnnotation(LogModule.class).value();
        operLog.setOperation(module);
        //获取方法参数,结果,方法名
        String string = Arrays.toString(joinPoint.getArgs());

        operLog.setParam(string);
        Object result = null;

            result = joinPoint.proceed();

        if(result!=null){
            operLog.setResult(result.toString());
            log.info("日志记录{}", operLog);
            logMapper.insert(operLog);
        }
        return result;
    }

}
